package com.fowo.api.common.util;

import lombok.experimental.UtilityClass;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** 请求参数处理 */
@UtilityClass
public class RequestParameterUtils {
    public static String get(Map<String, List<String>> requestParameterMap, String name) {
        if (requestParameterMap == null) {
            return null;
        }
        final List<String> strings = requestParameterMap.get(name);
        if (strings.size() > 0) {
            return ListUtils.join(", ", strings);
        }
        return null;
    }

    public static Map<String, List<String>> parseQueryString(String queryString) {
        if(!StringUtils.hasText(queryString)) {
            return null;
        }
        Map<String, List<String>> params = new ConcurrentHashMap<>();
        final String[] parts = queryString.split("&");
        for(String part : parts) {
            int eqPos = part.indexOf('=');
            String name;
            String value = null;
            if (eqPos == -1) {
                name = part;
            } else {
                name = part.substring(0, eqPos);
                value = part.substring(eqPos + 1);
            }
            name = URLDecoder.decode(name, StandardCharsets.UTF_8);
            List<String> strings = params.computeIfAbsent(name, k -> new ArrayList<>());
            if (value != null) {
                value = URLDecoder.decode(value, StandardCharsets.UTF_8);
            }
            strings.add(value);
        }
        return params;
    }
}
